#include <websocketpp/config/asio.hpp>
#include <websocketpp/server.hpp>
#include <iostream>

typedef websocketpp::server<websocketpp::config::asio_tls> server_tls;

// TLS 初始化处理函数
context_ptr on_tls_init(websocketpp::connection_hdl hdl) {
    context_ptr ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);
    
    try {
        ctx->set_options(boost::asio::ssl::context::default_workarounds |
                        boost::asio::ssl::context::no_sslv2 |
                        boost::asio::ssl::context::no_sslv3 |
                        boost::asio::ssl::context::single_dh_use);
        
        // 设置证书和私钥路径
        ctx->use_certificate_chain_file("server.pem");
        ctx->use_private_key_file("server.pem", boost::asio::ssl::context::pem);
    } catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }
    return ctx;
}

void on_message(server_tls* s, websocketpp::connection_hdl hdl, server_tls::message_ptr msg) {
    std::cout << "Received message: " << msg->get_payload() << std::endl;
    s->send(hdl, msg->get_payload(), msg->get_opcode());
}

int main() {
    server_tls ws_server;
    
    ws_server.set_access_channels(websocketpp::log::alevel::all);
    ws_server.clear_access_channels(websocketpp::log::alevel::frame_payload);
    
    // 设置 TLS 初始化处理函数
    ws_server.set_tls_init_handler(bind(&on_tls_init, ::_1));
    
    // 设置消息处理函数
    ws_server.set_message_handler(bind(&on_message, &ws_server, ::_1, ::_2));
    
    ws_server.init_asio();
    ws_server.listen(9003);
    ws_server.start_accept();
    
    std::cout << "TLS Server starting on port 9003" << std::endl;
    ws_server.run();
    
    return 0;
}